package com.lucene.helloword;

import java.awt.event.ItemEvent;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;



import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class TestLuceneIndex {

		@Test
	    public void testIndex(){
	        LuceneTest luceneTest = new LuceneTest();
	        luceneTest.index();
	    }
	    //分词测试
	    @Test
	    public void analyzer() throws IOException {
	    	
	    	String txt="我在学习java高富帅";
	    	Analyzer analyzer=new IKAnalyzer(false);
	    	TokenStream tokenStream=analyzer.tokenStream("content", new StringReader(txt));//生成一个分词流
	    	CharTermAttribute termAttribute=tokenStream.addAttribute(CharTermAttribute.class);//为token设置属性类
	    	tokenStream.reset();//重新设置
	    	while (tokenStream.incrementToken()) {
	    		System.out.print(new String(termAttribute.buffer(), 0, termAttribute.length()) + "|");
				
			}
	    }
	    //查询测试
	    @SuppressWarnings("deprecation")
		@Test
	    public void query() throws IOException, ParseException{
	    	IndexReader reader=
	    			DirectoryReader.open(FSDirectory.open(new File("E:/lucene/index01")));//索引读取类
	    	IndexSearcher search=new IndexSearcher(reader);//搜索入口工具类
	    	String queryStr1="java";//关键字搜索
	    	BooleanQuery booleanQuery=new BooleanQuery();
	    	//条件一内容中必须有life内容
	    	QueryParser queryParser=new QueryParser(Version.LATEST,"content",new StandardAnalyzer(Version.LATEST));
	    	Query query1=queryParser.parse(queryStr1);
	    	Query query2=NumericRangeQuery.newIntRange("score", 60, null, true, false);
	    	Query query3=queryParser.parse("score");
	    	booleanQuery.add(query3,Occur.SHOULD);
	    	booleanQuery.add(query1,Occur.MUST);
	    	//booleanQuery.add(query2,Occur.MUST);
	    	TopDocs topDocs=search.search(booleanQuery, 100);//查询前100条数据
	    	System.out.println("查询结果总数----"+topDocs.totalHits);
	    	ScoreDoc scoreDoc[]=topDocs.scoreDocs;//得到所有结果集
	    	for(int i=0;i<scoreDoc.length;i++){
	    		int num=scoreDoc[i].doc;//得到文档id;
	    		Document document=search.doc(num);//拿到指定的文档
	    		System.out.println("内容======="+document.get("content"));//// 由于内容没有存储所以执行结果为null
	    		 System.out.println("id--" + num + "---scors--" + scoreDoc[i].score + "---index--" + scoreDoc[i].shardIndex);
	    	}
	    }
	    @Test
	    public void defaultSortTest() throws IOException, ParseException{
	    	IndexReader reader=DirectoryReader.open(FSDirectory.open(new File("E:/lucene/index01")));
	    	IndexSearcher searcher=new IndexSearcher(reader);//搜索入口工具类
	    	String queryStr="java";//搜索关键字
	    	QueryParser queryParser=new QueryParser(Version.LATEST,"content",new StandardAnalyzer(Version.LATEST));//实例查询条件类
	    	Query query=queryParser.parse(queryStr);
	    	TopDocs topdocs=searcher.search(query, 100);//查询前100记录
	    	System.out.println("查询总数---"+topdocs.totalHits);
	    	ScoreDoc scores[] = topdocs.scoreDocs;// 得到所有结果集
	        for (int i = 0; i < scores.length; i++) {
	            int num = scores[i].doc;// 得到文档id
	            Document document = searcher.doc(num);// 拿到指定的文档
	            System.out.println("内容====" + document.get("content"));// 由于内容没有存储所以执行结果为null
	            System.out.println("id--" + num + "---scors--" + scores[i].score + "---index--" + scores[i].shardIndex);
	        }
	    }
	    
	    //高亮测试
	    @Test
	    public void highlighter() throws IOException, ParseException, InvalidTokenOffsetsException{
	    	
	    	IndexReader reader=DirectoryReader.open(FSDirectory.open(new File("E:/lucene/index01")));
	    	//搜索入口工具类
	    	IndexSearcher search=new IndexSearcher(reader);
	    	//中文分词器
	    	Analyzer analyzer=new IKAnalyzer();
	    	//实例查询条件类
	    	QueryParser queryParser=new QueryParser("content",analyzer);
	    	Query query=queryParser.parse("java");
	    	TopDocs topDocs=search.search(query, 100);//查询前100记录
	    	System.out.println("共查询出："+topDocs.totalHits+"条数据");
	    	ScoreDoc scoreDoc[]=topDocs.scoreDocs;//结果集
	    	//高亮// 高亮html格式
	    	Formatter formatter=new SimpleHTMLFormatter("<font color='red'>", "</font>");
	    	Scorer scorer=new QueryScorer(query);//检查评分
	    	Fragmenter fragmenter=new SimpleFragmenter(100);//设置最大片段为100
	    	Highlighter highlighter=new Highlighter(formatter,scorer);//高亮显示类
	    	highlighter.setTextFragmenter(fragmenter);//设置格式
	    	for (int i = 0; i < scoreDoc.length; i++) {// 遍历结果集
	            int docnum = scoreDoc[i].doc;
	            Document doc = search.doc(docnum);
	            String content = doc.get("content");
	            System.out.println(content);// 原内容
	            if (content != null) {
	                TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(content));
	                String str = highlighter.getBestFragment(tokenStream, content);// 得到高亮显示后的内容
	                System.out.println(str);
	            }
	        }

	    }
	    
	    @Test
	    public void pageTest() throws IOException, ParseException {
	        IndexReader reader = DirectoryReader.open(FSDirectory.open(new File("E:/lucene/index01")));// 索引读取类
	        IndexSearcher search = new IndexSearcher(reader);// 搜索入口工具类
	        String queryStr = "Java";// 搜索关键字
	        QueryParser queryParser = new QueryParser("content", new StandardAnalyzer(Version.LUCENE_44.LUCENE_44));// 实例查询条件类
	        Query query = queryParser.parse(queryStr);// 查询
	        TopScoreDocCollector results = TopScoreDocCollector.create(100, false);// 结果集
	        search.search(query, results);// 查询前100条
	        TopDocs topdocs = results.topDocs(1, 2);// 从结果集中第1条开始取2条
	        ScoreDoc scores[] = topdocs.scoreDocs;// 得到所有结果集
	        for (int i = 0; i < scores.length; i++) {
	            int num = scores[i].doc;// 得到文档id
	            Document document = search.doc(num);// 拿到指定的文档
	            System.out.println("内容====" + document.get("content"));// 由于内容没有存储所以执行结果为null
	            System.out.println("id--" + num + "---scors--" + scores[i].score + "---index--" + scores[i].shardIndex);
	        }
	    }
	    
}
